/*
Copyright 2007 Nathan Baker

This file is part of XAliens.

XAliens is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

XAliens is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with XAliens.  If not, see <http://www.gnu.org/licenses/>.
 */

package sprites;

import utils.StopWatch;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.ArrayList;

public class AnimatedEntity extends Entity {

    private ArrayList<BufferedImage> _imageList = new ArrayList<BufferedImage>();
    private int _currentFrame = 0;
    private int _timerInterval = 50;
    private StopWatch _timer = new StopWatch();

    /**
     *
     */
    protected AnimatedEntity() {
        _timer.start();
    }

    /**
     * @param img
     */
    protected AnimatedEntity(BufferedImage img) {
        super(img);
    }

    /**
     *
     */
    public void nextFrame() {
        this.mImage = _imageList.get(_currentFrame);
        mImageH = _imageList.get(_currentFrame).getHeight();
        mImageW = _imageList.get(_currentFrame).getWidth();
        _currentFrame++;
        if (_currentFrame >= _imageList.size()) {
            _currentFrame = 0;
        }
    }

    @Override
    public void draw(Graphics2D g) {
        if (checkTimer()) {
            nextFrame();
            _timer.start();
        }
        super.draw(g);
    }

    /**
     * Checks if the interval for this frame has elapsed
     *
     * @return
     */
    private boolean checkTimer() {
        return _timer.getElapsedTime() >= _timerInterval;
    }

    public void addFrame(BufferedImage img) {
        _imageList.add(img);
        mImageH = _imageList.get(_currentFrame).getHeight();
        mImageW = _imageList.get(_currentFrame).getWidth();
    }

    @Override
    public int getWidth() {
        return _imageList.get(_currentFrame).getWidth();
    }

    public int getHeight() {
        return _imageList.get(_currentFrame).getHeight();
    }
}
